package org.bopis.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.bopis.form.BusquedaMarcasForm;
import org.bopis.services.impl.MarcaServiceImpl;
import org.bopis.services.interfaz.MarcasService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.boole.dao.BopiDAO;
import com.boole.model.Bopi;
import com.boole.model.Marca;


/**
 * Clase que gestiona todas las operaciones que tengan que ver con la busqueda de marcas
 * @author i-fernandezmolina
 *
 */
public class BusquedaMarcasActions extends CustomDispatchAction {

	
	/**
	 * Este metodo carga los datos necesarios para la busqueda avanzada de marcas
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward loadAdvancedSearch(ActionMapping mapping, ActionForm form,
			  HttpServletRequest request, HttpServletResponse response)
			  throws Exception {
		
		return mapping.findForward("Success");
	}
	
	/**
	 * Este metodo realiza la busqueda avanzada de marcas
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward search(ActionMapping mapping, ActionForm form,
			  HttpServletRequest request, HttpServletResponse response)
			  throws Exception {
		
		BusquedaMarcasForm bForm = (BusquedaMarcasForm) form;
		
		MarcasService marcasService = new MarcaServiceImpl();
		List<Marca> lstMarcas = marcasService.search(bForm);
		
		super.addObjectToRequest(request, "lstMarcas", lstMarcas);
			
		return mapping.findForward("Success");
	}
	
	public ActionForward searchMarca(ActionMapping mapping, ActionForm form,
			  HttpServletRequest request, HttpServletResponse response)
			  throws Exception {
		
		BusquedaMarcasForm bForm = (BusquedaMarcasForm) form;
		
		MarcasService marcasService = new MarcaServiceImpl();
		Marca marca = marcasService.searchById(Long.valueOf(bForm.getIdMarca()));
		
		//TODO ESTO HAY QUE MEJORARLO QUE YA ESTOY CANSADO
		ApplicationContext context = new ClassPathXmlApplicationContext("SpringModule.xml");
		BopiDAO bopiDAO = (BopiDAO) context.getBean("bopiDAO");
		Bopi bopi = bopiDAO.searchById(marca.getIdBopi());
		
		marca.setBopi(bopi);
		
		super.addObjectToRequest(request, "marca", marca);
				
		return mapping.findForward("Success");
	}
	
	
}
